package com.demo.quartzJob;

import org.quartz.SchedulerException;

import com.common.plugin.QuartzPlugin;
import com.demo.common.model.QuartzJob;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;

public class QuartzJobController extends Controller {
	
	private static final Log log = Log.getLog(QuartzJobController.class);
	
	public void index() {
		setAttr("quartzPage", QuartzJob.dao.paginate(getParaToInt(0, 1), 10));
		render("list.html");
	}

	public void add() {
	}

	public void save() {
		//保存数据
		QuartzJob quartzJob = getModel(QuartzJob.class);
		//启动定时任务
		try {
			QuartzPlugin.manager.initJob(quartzJob, Class.forName(quartzJob.getJobClassName()));
			quartzJob.save();
			redirect("/quartz");
		} catch (ClassNotFoundException e) {
			log.error("启动定时任务失败!" + quartzJob.getJobClassName() + "不存在:" + e.getMessage(), e);
			e.printStackTrace();
			renderError(403);
		} catch (SchedulerException e) {
			log.error("启动定时任务失败!" + e.getMessage(), e);
			e.printStackTrace();
		}
	}

	public void edit() {
		setAttr("quartzJob", QuartzJob.dao.findById(getParaToInt()));
	}

	public void update() {
		QuartzJob quartzJob = getModel(QuartzJob.class);
		quartzJob.setJobStatus(QuartzPlugin.STATUS_PAUSE);
		try {
			QuartzPlugin.manager.pauseJob(quartzJob);
			quartzJob.update();
			redirect("/quartz");
		} catch (SchedulerException e) {
			e.printStackTrace();
			renderError(403);
		}
		
	}
	
	/**
	 * 逻辑删除
	 * */
	public void delete() {
		QuartzJob quartzJob = QuartzJob.dao.findById(getParaToInt());
		quartzJob.setJobStatus(QuartzPlugin.STATUS_DEL);
		try {
			QuartzPlugin.manager.deleteJob(quartzJob);
			quartzJob.update();
			redirect("/quartz");
		} catch (SchedulerException e) {
			log.error("删除定时任务发生异常:" + e.getMessage(), e);
			renderError(403);
		}
	}
	
	/**
	 * 恢复定时任务
	 * */
	public void resume() {
		QuartzJob quartzJob = QuartzJob.dao.findById(getParaToInt());
		try {
			QuartzPlugin.manager.resumeJob(quartzJob);
			quartzJob.setJobStatus(QuartzPlugin.STATUS_RESUME);
			quartzJob.update();
			redirect("/quartz");
		} catch (Exception e) {
			log.error("恢复定时任务发生异常:" + e.getMessage(), e);
			renderError(403);
		}
	}
	
	/**
	 * 暂停定时任务
	 * */
	public void pause() {
		QuartzJob quartzJob = QuartzJob.dao.findById(getParaToInt());
		try {
			QuartzPlugin.manager.pauseJob(quartzJob);
			quartzJob.setJobStatus(QuartzPlugin.STATUS_PAUSE);
			quartzJob.update();
			redirect("/quartz");
		} catch (Exception e) {
			log.error("暂停定时任务发生异常:" + e.getMessage(), e);
			renderError(403);
		}
		
	}
}
